package com.gitee.dolt.weixin.mp.aspect;

import cn.hutool.json.JSONUtil;
import com.gitee.dolt.core.exception.InternalServerException;
import com.gitee.dolt.core.util.SpringUtils;
import com.gitee.dolt.weixin.mp.entity.WxMpMsgSendLogDTO;
import com.gitee.dolt.weixin.mp.event.WxMpMsgSendLogEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.time.LocalDateTime;

/**
 * SysLock锁切面
 *
 * @author LYH
 */
@RequiredArgsConstructor
@Slf4j
@Aspect
public class WxMpServiceAspect {

    @Pointcut("execution(public * me.chanjar.weixin.mp.api.impl.WxMpTemplateMsgServiceImpl.sendTemplateMsg(..))")
    public void wxMpServiceAspect() {

    }

    @Around("wxMpServiceAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws WxErrorException {
        Object[] args = joinPoint.getArgs();
        WxMpTemplateMessage wxMpTemplateMessage = null;
        for (Object arg : args) {
            if (arg instanceof WxMpTemplateMessage) {
                wxMpTemplateMessage = (WxMpTemplateMessage) arg;
            }
        }
        if (wxMpTemplateMessage == null) {
            throw new InternalServerException("签名参数错误");
        }
        WxMpMsgSendLogDTO wxMpMsgSendLogDTO = new WxMpMsgSendLogDTO()
                .setTemplateId(wxMpTemplateMessage.getTemplateId())
                .setToUser(wxMpTemplateMessage.getToUser())
                .setUrl(wxMpTemplateMessage.getUrl())
                .setBeginDate(LocalDateTime.now())
                .setData(JSONUtil.toJsonStr(wxMpTemplateMessage.getData()));

        try {
            Object result = joinPoint.proceed();
            wxMpMsgSendLogDTO.setMsgId((String) result);
            wxMpMsgSendLogDTO.setSuccess(true);
            return result;
        } catch (WxErrorException e) {
            wxMpMsgSendLogDTO.setSuccess(false)
                    .setMessage(e.getMessage());
            throw e;
        } catch (Throwable e) {
            throw new InternalServerException("微信公众号发送模板消息异常");
        } finally {
            SpringUtils.publishEvent(new WxMpMsgSendLogEvent(wxMpMsgSendLogDTO));
        }

    }

}
